package com.saguitech.sgemeos.ui.adapters;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import android.content.Context;
import android.widget.SimpleExpandableListAdapter;

import com.saguitech.sgemeos.R;
import com.saguitech.sgemeos.business.ExpositionBusiness;

public class ExpositionsAdapter extends SimpleExpandableListAdapter {

	static final String[] groupFrom = { "name" };
	static final int[] groupTo = { R.id.nameGroupTV };

	static final String[] childFrom = { "id", "title", "date", "time" };
	static final int[] childTo = { R.id.idChildTV ,R.id.titleChildTV, R.id.dateChildTV, R.id.timeChildTV };

	public static List<Map<String, String>> getGroups(
			List<ExpositionBusiness> expositions) {
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		Set<String> groups = new TreeSet<String>();
		for (ExpositionBusiness e : expositions) {
			groups.add(e.getType());
		}
		for (String s : groups) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("name", s);
			result.add(map);
		}
		return result;
	}

	public static List<List<Map<String, String>>> getChilds(
			List<Map<String, String>> groups,
			List<ExpositionBusiness> expositions) {
		List<List<Map<String, String>>> result = new ArrayList<List<Map<String, String>>>();
		Map<String, List<Map<String, String>>> groupChildLists = new HashMap<String, List<Map<String, String>>>();
		for (ExpositionBusiness expo : expositions) {
			if (groupChildLists.containsKey(expo.getType())) {
				groupChildLists.get(expo.getType()).add(getChildMap(expo));
			} else {
				List<Map<String, String>> childList = new ArrayList<Map<String, String>>();
				childList.add(getChildMap(expo));
				groupChildLists.put(expo.getType(), childList);
			}
		}
		for (Map<String, String> m : groups)
			result.add(groupChildLists.get(m.get("name")));
		return result;
	}

	private static Map<String, String> getChildMap(ExpositionBusiness expo) {
		Map<String, String> dataRow = new HashMap<String, String>();
		dataRow.put("id", String.valueOf(expo.getId()));
		dataRow.put("title", expo.getTitle());
		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		dataRow.put("date",
				formatter.format(expo.getTimeList().get(expo.getIndexTimeToShow()).getInitialTime()));
		formatter = new SimpleDateFormat("HH:mm");
		dataRow.put("time",
				formatter.format(expo.getTimeList().get(expo.getIndexTimeToShow()).getInitialTime()));
		return dataRow;
	}

	public ExpositionsAdapter(Context context,
			List<Map<String, String>> groupData,
			List<List<Map<String, String>>> childData) {
		super(context, groupData, R.layout.group_exposition_row, groupFrom,
				groupTo, childData, R.layout.child_exposition_row, childFrom,
				childTo);

	}

}
